package com.example.watchcat2k.finalproject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class LoginUserActivity extends AppCompatActivity {

    ImageView imageView;
    EditText account;
    EditText password;
    Button login;
    Button clear;
    TextView goto_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        init();
        set_click();

    }

    void init(){
        imageView = findViewById(R.id.imageView);
        account = findViewById(R.id.Login_username);
        password = findViewById(R.id.Login_password);

        login = findViewById(R.id.Login_OK);
        clear = findViewById(R.id.Login_clear);

        goto_register = findViewById(R.id.Goto_register);
    }

    void set_click(){
        //登陆
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username_ = account.getText().toString();
                String password_ = password.getText().toString();
                if(username_.equals("")){
                    Toast.makeText(LoginUserActivity.this, "用户名不可为空", Toast.LENGTH_SHORT).show();
                }
                else if(username_.equals("")){
                    Toast.makeText(LoginUserActivity.this, "密码不可为空", Toast.LENGTH_SHORT).show();
                }
                else{

                    //判断网络是否开启
                    ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cn.getActiveNetworkInfo();
                    if (networkInfo == null || !networkInfo.isConnected()) {
                        Toast.makeText(LoginUserActivity.this, "网络未连接", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Login_packet login_packet = new Login_packet(username_, password_);

                    //登陆网络请求
                    try {
                        OkHttpClient build = new OkHttpClient.Builder()
                                .connectTimeout(2, TimeUnit.SECONDS)
                                .readTimeout(2, TimeUnit.SECONDS)
                                .writeTimeout(2, TimeUnit.SECONDS)
                                .build();

                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("http://129.204.116.253:8080")

                                .addConverterFactory(GsonConverterFactory.create())

                                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                                // build 即为okhttp声明的变量，下文会讲
                                .client(build)

                                .build();

                        LoginInterface service = retrofit.create(LoginInterface.class);
                        service.postRegister(login_packet)
                                .subscribeOn(Schedulers.io())//请求在新的线程中执行
                                .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                                .subscribe(new DisposableObserver<Confirm_packet_login>() {
                                    @Override
                                    public void onNext(Confirm_packet_login confirm_packet_login) {
                                        if(confirm_packet_login.getStatus()){
                                            User_basic_info user_basic_info = new User_basic_info(username_, confirm_packet_login.getName(),
                                                    confirm_packet_login.getDescription(),confirm_packet_login.getIcon());

                                            Intent intent = new Intent(LoginUserActivity.this, MainActivity.class);
                                            intent.putExtra("user", user_basic_info);
                                            intent.putExtra("register", false);
                                            startActivity(intent);
                                        }
                                        else {
                                            Toast.makeText(LoginUserActivity.this, "失败: " + confirm_packet_login.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Toast.makeText(LoginUserActivity.this, "访问失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                        Log.i("test", "onError: "+e.toString());
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    }catch (Exception o){
                        Toast.makeText(LoginUserActivity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
                        Log.i("test", "onError: "+o.toString());
                    }
                }
            }
        });



        //清空
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account.setText("");
                password.setText("");
            }
        });

        goto_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginUserActivity.this, RegisterUserActivity.class);
                startActivity(intent);
            }
        });
    }

    public interface LoginInterface{
        @POST("/signin")
        Observable<Confirm_packet_login> postRegister(@Body Login_packet login_packet);
    }

}
